
<template>
  <div>
    <!-- 整体播放器 -->
    <div class="player" v-if="showplayer">
      <div class="button" @click="showplayer = false">
        <span class="iconfont icon-xiangxia"></span>
      </div>
      <div class="title">
        <h2>{{ SongDetail.name }}</h2>
        <h3>
          <span v-for="(key, index) in SongDetail.ar" :key="index"
            >{{ key.name }} &nbsp;&nbsp;</span
          >
        </h3>
      </div>
      <div class="content">
        <div
          :class="['img', 'play', { pause: iconplay }]"
          v-show="togglelyric == true"
          @click="togglelyric = false"
        >
          <img :src="SongDetail.al.picUrl" />
        </div>
        <div
          class="lyrics"
          v-show="togglelyric != true"
          @click="togglelyric = true"
        >
          <ul :style="{ top: lyricTop }">
            <li
              v-for="(item, index) in lyric"
              :key="index"
              :class="{ con: currentRow == index }"
            >
              {{ item.text }}
            </li>
          </ul>
        </div>
      </div>
      <div class="range">
        <div class="bar">
          <span class="timeLeft">{{ timeLeft | playerTime }}</span>
          <van-slider
            bar-height="4px"
            active-color="#ee0a24"
            v-model="value"
            @change="sliderchange"
            @input="lyricInput"
          >
            <template #button>
              <div class="custom-button"></div>
            </template>
          </van-slider>
          <span class="timeRight">{{ timeRight | playerTime }}</span>
        </div>
      </div>
      <div class="buttons">
        <div
          v-show="playerType == 1"
          class="iconfont icon-icon__xunhuan"
          @click="changeMode"
        ></div>
        <div
          v-show="playerType == 2"
          class="iconfont icon-random"
          @click="changeMode"
        ></div>
        <div class="iconfont icon-48shangyishou" @click="prevSong"></div>
        <div
          :class="[
            'iconfont',
            iconplay ? 'icon-bofang' : 'icon-tianchongxing-',
            'center',
          ]"
          @click.stop="toggleplay"
        ></div>
        <div class="iconfont icon-048caozuo_xiayishou" @click="nextSong"></div>
        <div
          :class="[
            'iconfont',
            { 'icon-aixin': flag == false },
            { 'icon-aixin1': flag == true },
          ]"
          @click="collection"
        ></div>
      </div>
    </div>

    <!-- 迷你播放器 -->
    <div class="mini_player">
      <div
        :class="['img', 'play', { pause: iconplay }]"
        @click="showplayer = true"
      >
        <img :src="SongDetail.al.picUrl" />
      </div>
      <div class="text">
        <h2>{{ SongDetail.name }}</h2>
        <h3>
          <span v-for="(key, index) in SongDetail.ar" :key="index"
            >{{ key.name }} &nbsp;&nbsp;</span
          >
          <!-- <span v-show="SongDetail.ar.length >= 2 ? true : false">/</span> -->
        </h3>
      </div>
      <!-- 停止冒泡  click.stop-->
      <div class="control" @click.stop="toggleplay">
        <span
          :class="[
            'iconfont',
            iconplay ? 'icon-bofang' : 'icon-tianchongxing-',
            'center',
          ]"
        ></span>
      </div>
      <div class="list" @click.stop="isMusicPlayList = true">
        <span class="iconfont icon-icon-"></span>
      </div>
    </div>
    <!-- 音乐播放列表 -->
    <div class="musicPlayList" v-if="isMusicPlayList">
      <div class="musicList">
        <h1>
          <i class="iconfont icon-icon__xunhuan"></i>顺序播放({{ playLists.length }})
        </h1>
        <span class="iconfont icon-shanchu1" @click="clearAll"></span>
      </div>
      <dl>
        <dd
          v-for="(item, index) in playLists"
          :key="index"
          @click="editPlayerId(item.id)"
        >
          <p>
            <i v-if="item.id == playerId" class="iconfont icon-laba"></i
            >{{ item.name }}
          </p>
          <span class="iconfont icon-shanchu" @click="del(index)"></span>
        </dd>
      </dl>
      <div class="button" @click="isMusicPlayList = false">关闭</div>
    </div>
    <!-- // 当浏览器能够开始播放指定的音频/视频时，会发生 canplay 事件。 -->
    <audio
      :src="musicData"
      ref="audio"
      @canplay="canplayFn"
      @ended="endedFun"
      autoplay
    ></audio>
  </div>
</template>
 

<script>
import { getSongUrl, getSongDetail, getLyric } from "../api/song.js";
import { getPlaylistDetail } from "../api/rank";

export default {
  props: ["playerId", "newMuics", "listId"],
  data() {
    return {
      currentRow: 0, //歌词高亮
      lyric: [], //歌词
      lyricTop: "210px",
      togglelyric: true,
      playerType: 1,
      isMusicPlayList: false,
      musicData: [],
      SongDetail: {
        al: {
          picUrl: null,
        },
      },
      iconplay: true,
      showplayer: false,
      timeRight: 0,
      timeLeft: 0,
      clearset: null,
      value: 0,
      playindex: null,
      subindex: null,
      loopStaus: null,
      flag: false,
      playLists: [],
      views: false,
    };
  },
  methods: {
    getSongUrlFn() {
      // 这是获取单独的一首歌曲的音频地址
      getSongUrl({ id: this.playerId }).then((data) => {
        // console.log("数据", data);
        this.musicData = data.data[0].url;
      });
    },
    // 这是单独的一首歌的信息
    getSongDetailFn() {
      getSongDetail({ ids: this.playerId }).then((data) => {
        // console.log("数据", data);
        this.SongDetail = data.songs[0];

        // this.SongDetail = data.songs[0];
        // console.log("这是单独的一首歌", this.SongDetail);
        // 判断播放列表是否有相同数据，没有吧歌曲放入列表中
        let index = this.playLists.findIndex((item) => {
          return item.id == this.SongDetail.id;
        });
        if (index == "-1") {
          this.playLists.push(this.SongDetail);
        }
      });
    },
    // 调用接口获取歌词
    getLyricFn() {
      getLyric({ id: this.playerId }).then((data) => {
        // console.log(data);
        this.formatLyric(data.lrc.lyric);
      });
    },
    // 处理歌词结构
    formatLyric(text) {
      // 让每次调用这个函数时，数组都为空
      this.lyric = [];
      //把原歌曲字符串转歌词
      let arr = text.split("\n");
      //获取数组长度
      let row = arr.length;
      for (let i = 0; i < row; i++) {
        //获取数据"[00:00.000] 作词 : 陈镇川"
        let temp_row = arr[i];
        // 打印的是字符串类型
        // console.log("类型",temp_row);
        // 将每一项的temp_row进行剪切
        let temp_arr = temp_row.split("]"); //分成两个数组
        //删除数组最后一个，返回修改后的数据
        let lyrictext = temp_arr.pop();
        let obj = {};
        //  把歌词添加进对象中
        obj.text = lyrictext;
        temp_arr.forEach((item) => {
          // "[00:21.45" =>00:21.45
          let time_arr = item.substr(1, item.length - 1).split(":");
          //得到当前秒数
          let s = time_arr[0] * 60 + Math.ceil(time_arr[1]);
          //  把时间添加进对象中
          obj.time = s;
        });
        if (lyrictext.length > 0) {
          //每一行处理好数据放入数组中
          this.lyric.push(obj);
        }
        // console.log("obj对象", obj);
      }
    },
    collection() {
      // this.playLists[]
      // this.views = true;
      this.flag = !this.flag;
      if (this.flag) {
        this.loveSongs = this.playLists;
        this.views = true;
      }
      this.$emit("collection", {
        loveSongs: this.loveSongs,
        views: this.views,
      });
      console.log("收藏", this.loveSongs);
      // console.log( this.flag);
    },
    // 点击播放按钮播放/停止
    toggleplay() {
      if (this.iconplay) {
        // 播放音频
        this.$refs.audio.play();
        this.viewTime();
      } else {
        this.$refs.audio.pause();
        clearInterval(this.clearset);
      }
      this.iconplay = !this.iconplay;
    },
    viewTime() {
      clearInterval(this.clearset);
      this.clearset = setInterval(() => {
        let currentTime = this.$refs.audio.currentTime;
        let duration = this.$refs.audio.duration;
        this.timeLeft = currentTime;
        // 计算滚动条效果
        this.value = (currentTime / duration) * 100;
        if (this.value == 100) {
          clearInterval(this.clearset);
          this.$refs.audio.pause();
          this.iconplay = true;
        }
      }, 1002);
    },
    endedFun() {
      this.iconplay = true;
      if (this.playerType == 1) {
        // 下一首
        this.nextSong();
      } else if (this.playerType == 2) {
        let index = parseInt(Math.random() * this.playLists.length);
        this.$emit("get-player-id", this.playLists[index].id); //修改父组件值
      } else {
        //  这是循环播放的
        this.$refs.audio.play();
        this.iconplay = false;
      }
    },
    // 当浏览器能够开始播放指定的音频/视频时，会发生 canplay 事件。
    canplayFn() {
      // this.$refs.audio.play();
      // 音频总时长
      let duration = this.$refs.audio.duration;
      this.timeRight = duration;
    },
    sliderchange() {
      let allTime = (this.$refs.audio.duration * this.value) / 100;
      // 修改页面的播放进度
      this.timeLeft = allTime;
      // 修改音频的播放进度
      this.$refs.audio.currentTime = allTime;
    },
    //滑动滚动条时 实时动态显示歌词变化
    lyricInput() {
      let allTime = parseInt((this.$refs.audio.duration * this.value) / 100);
      for (let i = 0; i < this.lyric.length; i++) {
        if (allTime == this.lyric[i].time) {
          this.lyricTop = 210 - i * 36 + "px";
          //歌词高亮
          this.currentRow = i;
          break;
        }
      }
    },
    changeMode() {
      this.playerType = this.playerType == 1 ? 2 : 1;
    },
    prevSong() {
      // 获取点击歌曲的的id
      let id = this.SongDetail.id;
      // 或者使用解构的方法
      // let{id} = this.SongDetail;
      // 通过id来判断列表的下标
      let index = this.playLists.findIndex((item) => item.id == id);
      index -= 1;
      if (index < 0) {
        index = this.playLists.length - 1;
      }
      let npId = this.playLists[index].id;
      this.$emit("get-player-id", npId);
      // console.log("播放按键的状态", this.iconplay);
      // 此时的数据还没有请求完成，就已经执行完，所以没效果，需要在canplay调用
      // this.$refs.audio.play();
    },
    nextSong() {
      // 获取点击歌曲的的id
      let id = this.SongDetail.id;
      // 或者使用解构的方法
      // let{id} = this.SongDetail;
      // 通过id来判断列表的下标
      let index = this.playLists.findIndex((item) => item.id == id);
      index += 1;
      if (index >= this.playLists.length) {
        index = 0;
      }
      let npId = this.playLists[index].id;
      this.$emit("get-player-id", npId);
      // console.log("播放的npId", npId);
    },
    // 点击添加列表中的歌，播放
    editPlayerId(id) {
      this.$emit("get-player-id", id);
    },
    clearAll() {
      this.playLists = [];
    },
    del(index) {
      this.playLists.splice(index, 1);
    },
  },
  //   点击歌曲之后获取id，通过监听 id的变化再执行数据的获取
  watch: {
    playerId() {
      this.getSongUrlFn();
      this.getSongDetailFn();
      this.getLyricFn();
      this.iconplay = false;
      this.viewTime();
    },
    newMuics() {
      if (this.newMuics) {
        this.iconplay = false;
        this.$refs.audio.pause();
      }
      // this.$refs.audio.play();
      this.viewTime();
      this.iconplay = true;
    },
    listId() {
      getPlaylistDetail({ id: this.listId }).then((data) => {
        // console.log(data);
        this.playLists = data.playlist.tracks;
      });
    },
    timeLeft() {
      for (let i = 0; i < this.lyric.length; i++) {
        if (parseInt(this.timeLeft) == this.lyric[i].time) {
          // 向上移动相应的距离
          this.lyricTop = 210 - i * 36 + "px";
          //歌词高亮
          this.currentRow = i;
        }
      }
    },
  },
  filters: {
    playerTime(data) {
      let m = parseInt(data / 60);
      let s = parseInt(data % 60);
      m = m < 10 ? "0" + m : m;
      s = s < 10 ? "0" + s : s;
      return m + ":" + s;
    },
  },
};
</script>

<style lang="less" scoped>
// 整体播放器样式
.player {
  user-select: none;
  position: fixed;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  background: #817c7a;
  z-index: 900;
  .button {
    position: absolute;
    width: 20px;
    font-weight: bold;
    top: 14px;
    left: 14px;
    .iconfont {
      font-size: 22px;
      color: #fff;
    }
  }
  .title {
    text-align: center;
    color: #fff;
    h2 {
      font-size: 16px;
      margin-top: 10px;
    }
    h3 {
      font-size: 12px;
      // color: #888;
    }
  }
  .content {
    margin-top: 10px;
    height: 435px;
    width: 100%;
    position: relative;
    .img {
      width: 275px;
      height: 275px;
      border: 12px solid #96908d;
      position: absolute;
      top: 0px;
      left: 0px;
      right: 0px;
      bottom: 0px;
      margin: auto;
      border-radius: 50%;
      user-select: none;
      img {
        width: 100%;
        border-radius: 50%;
      }
      &.play {
        animation: rotate 20s linear infinite;
      }
      &.pause {
        animation-play-state: paused;
      }
    }
    .lyrics {
      width: 100%;
      height: 445px;
      position: relative;
      overflow: hidden;
    }
    ul {
      position: absolute;
      width: 100%;
      text-align: center;
      top: 210px;
      left: 0px;
      li {
        height: 36px;
        line-height: 36px;
        color: #cbcccc;
        font-size: 16px;
        &.con {
          color: #fff;
        }
      }
    }
  }
  .range {
    position: absolute;
    bottom: 82px;
    text-align: center;
    height: 20px;
    width: 100%;
    .bar {
      width: 246px;
      margin: 0 auto;
      color: #fff;
      position: relative;
      font-size: 12px;
      .timeLeft {
        position: absolute;
        left: -36px;
        top: -4px;
      }
      .timeRight {
        position: absolute;
        right: -36px;
        top: -4px;
      }
    }
  }
  .buttons {
    display: flex;
    position: absolute;
    bottom: 40px;
    width: 100%;

    .iconfont {
      flex: 1;
      width: 20%;
      text-align: center;
      font-size: 24px;
      line-height: 38px;
      color: #fff;
      cursor: default;
      user-select: none;
      &.center {
        font-size: 38px;
      }
    }
    .icon-aixin1 {
      color: red;
    }
  }
}
.custom-button {
  width: 6px;
  height: 6px;
  border: 5px solid #fff;
  background-color: #ee0a24;
  border-radius: 50%;
  user-select: none;
}
// 迷你样式
.mini_player {
  //  min-width: 320px;
  // max-width: 750px;
  // margin: 0 auto;
  width: 100%;
  position: fixed;
  left: 0;
  bottom: 0;
  height: 48px;
  background-color: #fff;
  user-select: none;
  box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.6);
  // background-color: rgb(137, 227, 243);
  display: flex;
  // justify-content: center;
  .img {
    flex: 0 0 55px;
    text-align: center;
    img {
      width: 36px;
      height: 36px;
      border-radius: 50%;
      margin: 6px auto;
      background-color: pink;
    }
  }
  .play {
    animation: rotate 20s linear infinite;
  }
  .pause {
    animation-play-state: paused;
  }
  .text {
    flex: 1;
    h2 {
      font-size: 16px;
      color: #1b1c1c;
      margin-top: 5px;
    }
    h3 {
      font-size: 12px;
      color: #929393;
    }
  }
  .control {
    flex: 0 0 36px;
    .iconfont {
      font-size: 29px;
      color: #474848;
      margin-top: 10px;
      display: inline-block;
    }
  }
}
.list {
  .iconfont {
    font-size: 30px;
    color: #474848;
    font-weight: 700;
    margin: 7px;
    display: inline-block;
  }
}
// 音乐播放列表
.musicPlayList {
  background-color: #fff;
  position: fixed;
  left: 0;
  bottom: 0;
  z-index: 850;
  width: 100%;
  height: 310px;
  border-radius: 5px 5px 0 0;
  user-select: none;
  .musicList {
    margin: 12px;
    height: 28px;
    line-height: 28px;
    position: relative;
    h1 {
      font-size: 16px;
      text-indent: 18px;
      i {
        font-size: 18px;
        margin-right: 8px;
        color: red;
      }
    }
    span.iconfont {
      display: inline-block;
      position: absolute;
      top: 2px;
      right: 25px;
      font-size: 18px;
    }
  }
  dl {
    height: 222px;
    overflow-y: scroll;
    dd {
      text-indent: 18px;
      font-size: 14px;
      height: 37px;
      line-height: 37px;
      position: relative;
      p {
        i {
          margin-right: 8px;
          color: red;
        }
        width: 80%;
        height: 37px;
        overflow: hidden;
      }
      span.iconfont {
        display: inline-block;
        position: absolute;
        top: 2px;
        right: 25px;
        font-size: 18px;
        color: red;
      }
    }
  }
  .button {
    height: 45px;
    line-height: 45px;
    text-align: center;
    font-size: 16px;
    position: absolute;
    left: 0px;
    bottom: 0px;
    width: 100%;
  }
}

@keyframes rotate {
  from {
    transform: rotate(0);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
